package com.oceansoft.mobile.econsole.modules.api.controller;

import com.oceansoft.mobile.econsole.modules.api.service.ISmsService;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

import static com.oceansoft.mobile.econsole.common.constant.Constant.BIZ_DICT;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 短信服务业务控制器
 *
 * @author chenw
 * @time 2014/8/26.
 */
@RestController
@RequestMapping("api/sms")
public class ApiSmsController extends BaseController {

    @Resource
    private ISmsService smsService;

    /**
     * 发送短信验证码
     *
     * @param telNum  手机号码
     * @param bizType 业务类型
     * @param content 消息内容
     * @param seconds 短信验证码过期时间 过期时间大于120秒则以120秒计
     * @return Result
     */
    @RequestMapping(value = "send", method = POST)
    public Result sendValidateCode(@RequestParam(value = "tel", required = true) String telNum,
                                   @RequestParam(value = "type", required = true) int bizType,
                                   @RequestParam(value = "content", required = false) String content,
                                   @RequestParam(value = "expire", required = false, defaultValue = "120")
                                           long seconds
    ) throws IOException {
        if (!StringUtils.hasText(telNum)) {
            return new Result(Result.FAILURE, "请输入手机号码");
        }
        String biz = BIZ_DICT.get(bizType);
        if (bizType < 0 || null == biz) {
            return new Result(Result.FAILURE, "业务编号不正确");
        }
        if (StringUtils.hasText(content) && content.length() > 100) {
            return new Result(Result.FAILURE, "短信内容过长，最大长度100字符");
        }

//        return smsService.createValidateCode(biz, telNum, StringUtils.hasText(content) ? content : "\u60a8\u83b7\u53d6\u7684\u82cf\u5dde\u516c\u5b89\u79fb\u52a8\u95e8\u6237\u9a8c\u8bc1\u7801\u4e3a", seconds > 1200 ? 1200 : seconds);
        return smsService.sendValidateCode(biz, telNum, content, seconds > 120 ? 120 : seconds);
    }


    @RequestMapping(value = "sendCode", method = POST)
    public Result sendValidateCode(@RequestParam(value = "tel") String phone,
                                   @RequestParam(value = "verCode") String verCode,
                                   @RequestParam(value = "verCodeKey") String verCodeKey,
                                   String forget) {
        return smsService.sendCodeMsg(phone, verCode, verCodeKey, forget);
    }
}
